﻿// 2023/3/20: 首个版本
// 2023/3/20: 优化对话框高度
// 2023/4/18: 针对中文环境优化对话框高度
// 2023/9/12: 修正英文日期显示
// 2023/9/22: 使用PassParent给ShowDialog传参
// 2023/9/25: 改为直接输入Icon对象

using System;
using System.IO;
using System.Xml;
using ASEva;
using ASEva.Samples;
using ASEva.Utility;
using ASEva.UIEto;
using Eto.Forms;
using Eto.Drawing;

namespace CommonSource
{
    class SingleSessionPicker : DialogPanel
    {
        public SingleSessionPicker(object caller, DateTime session, Icon icon = null)
        {
            this.session = session;

            Icon = icon;
            Title = chinese ? "数据截取工具" : "Session Picker";
            SetFixMode(600, 370, true);

            var mainLayout = this.SetContentAsColumnLayout();
            var tableLayout = mainLayout.AddTableLayout();
            var commonOptions = mainLayout.AddControl(new CommonPickOptionsControl(true), true) as CommonPickOptionsControl;
            var pickIDLayout = mainLayout.AddRowLayout();
            var rangeLayout = mainLayout.AddRowLayout();

            var row = tableLayout.AddRow();
            row.AddLabel(chinese ? "源数据片段：" : "Source Session:");
            row.AddLabel(session.ToString(chinese ? "yyyy/MM/dd HH:mm:ss" : "MM/dd/yyyy HH:mm:ss"));

            row = tableLayout.AddRow();
            row.AddLabel(chinese ? "输出路径：" : "Output path:");
            var linkPath = row.AddLinkButton(chinese ? "(未配置)" : "(Not configured)");
            linkPath.TextColor = Colors.Red;

            pickIDLayout.AddLabel(chinese ? "截取ID：" : "Pick ID:", TextAlignment.Left, false, 75);
            var textPickID = pickIDLayout.AddControl(new TextBox{ Text = defaultPickID }, true) as TextBox;

            rangeLayout.AddLabel(chinese ? "起始位置：" : "Pick from:", TextAlignment.Left, false, 75);
            var numStart = rangeLayout.AddControl(new NumericStepper()) as NumericStepper;
            rangeLayout.AddSpace();
            rangeLayout.AddLabel(chinese ? "截取长度：" : "Pick length:");
            var numLength = rangeLayout.AddControl(new NumericStepper()) as NumericStepper;
            rangeLayout.AddSpace();
            var buttonPick = rangeLayout.AddButton(chinese ? "截取" : "Pick", false, 80);
            buttonPick.Enabled = false;

            var sessionPath = Agency.GetSessionPath(session);
            var meta = sessionPath == null ? null : SessionMeta.Load(sessionPath + System.IO.Path.DirectorySeparatorChar + "meta.xml");
            if (meta == null || meta.Length == null)
            {
                delayShow(chinese ? "加载session信息失败。" : "Failed to load the session's informations.");
                return;
            }

            this.length = meta.Length.Value;
            if (this.length <= 5)
            {
                delayShow(chinese ? "Session长度太短，无法截取。" : "The session is too short to pick.");
                return;
            }
            numStart.MinValue = 0;
            numStart.MaxValue = this.length - 5;
            numStart.Value = 0;
            numLength.MinValue = 5;
            numLength.MaxValue = this.length;
            numLength.Value = 5;

            linkPath.Click += delegate
            {
                var dialog = new SelectFolderDialog();
                dialog.Title = chinese ? "请选择输出文件夹路径" : "Please choose the output path";
                if (dialog.ShowDialog(App.PassParent(this)) != DialogResult.Ok) return;

                linkPath.Text = dialog.Directory;
                linkPath.TextColor = Colors.Green;
                buttonPick.Enabled = true;
            };

            numStart.ValueChanged += delegate
            {
                numLength.MaxValue = length - (double)numStart.Value;
            };

            textPickID.TextChanged += delegate
            {
                if (textPickID.Text.Length == 0) textPickID.Text = defaultPickID;
            };

            buttonPick.Click += delegate
            {
                var dataPath = Agency.GetDataPath();

                var targetPath = linkPath.Text;
                if (dataPath != null && targetPath.IndexOf(dataPath + Path.DirectorySeparatorChar) >= 0)
                {
                    MessageBox.Show(chinese ? "截取数据不能存储在当前数据文件夹内。" : "Picked data can't be saved inside current data path.", "", MessageBoxType.Error);
                    return;
                }

                var pickConfig = new PickConfig();
                pickConfig.PickID = textPickID.Text.Length == 0 ? defaultPickID : textPickID.Text;
                pickConfig.Options = commonOptions.Options;

                var pick = new SingleSessionPick();
                pick.SourceSessionPath = Agency.GetSessionPath(session);
                pick.SourceSessionID = session;
                pick.SourceBeginTime = numStart.Value;
                pick.SourcePickLength = numLength.Value;

                var dstSessionID = session.AddSeconds((int)pick.SourceBeginTime);
                pick.DstSessionPath = targetPath + Path.DirectorySeparatorChar + dstSessionID.ToString("yyyyMMdd-HH-mm-ss");

                pick.SourceSubSessionPaths = new String[4];
                var subPaths = Agency.GetSubDataPathes();
                if (pick.SourceSessionPath.Length > dataPath.Length)
                {
                    var childPath = pick.SourceSessionPath.Substring(dataPath.Length + 1);
                    for (int i = 0; i < 4; i++)
                    {
                        if (i < subPaths.Length && subPaths[i] != null) pick.SourceSubSessionPaths[i] = subPaths[i] + Path.DirectorySeparatorChar + childPath;
                    }
                }

                pickConfig.Picks.Add(pick);

                String dummy = null;
                if (Agency.RunStandaloneTask(caller, "pick-session.system", pickConfig.ToXmlString(), out dummy) == TaskResult.RunOK)
                {
                    MessageBox.Show(chinese ? "Session截取成功。" : "Session picking finished.", "", MessageBoxType.Information);
                    Close();
                }
            };
        }

        private void delayShow(String msg)
        {
            showTimer = new UITimer();
            showTimer.Interval = 0.1;
            showTimer.Elapsed += delegate
            {
                showTimer.Stop();
                showTimer = null;
                MessageBox.Show(msg, "", MessageBoxType.Error);
                Close();
            };
            showTimer.Start();
        }

        private DateTime session;
        private double length;
        private String defaultPickID = "pick-" + DateTime.Now.ToString("yyyyMMddHHmmss");
        private UITimer showTimer;
        private bool chinese = Agency.GetAppLanguage() == "ch";
    }
}